package org.springblade.modules.notice.core.channel.impl;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.utils.message.domain.MessageParam;
import org.springblade.common.utils.message.domain.SendRequest;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.modules.notice.core.channel.BaseNoticeHandler;
import org.springblade.modules.notice.core.channel.NoticeHandler;
import org.springblade.modules.notice.enums.ChannelType;
import org.springblade.modules.notice.vo.NoticeTask;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

/**
 * @Author ysq
 * @Date 2024/11/26
 * @Description 飞书机器人通知处理类
 */
@Slf4j
@Component
public class FeiShuNoticeHandler extends BaseNoticeHandler implements NoticeHandler {

	public FeiShuNoticeHandler() {
		channelTypeCode = ChannelType.FEI_SHU_ROBOT.getCode();
	}

	@Override
	public void handle(NoticeTask task) throws Exception {
		log.info("飞书机器人通知处理 param: {}", JSONObject.toJSONString(task));
		// 没配置跳转地址时，默认跳转平台首页
		if (!task.getTemplateVariables().containsKey("url")) {
			task.getTemplateVariables().put("url", "https://admin.sida-tech.com/");
		}

		Map<String, Object> callback = MapUtil.ofEntries(
			MapUtil.entry("bizId", String.valueOf(task.getBizId())),
			MapUtil.entry(BladeConstant.MDC_TENANT_ID_KEY, task.getTenantId())
		);
		Optional.ofNullable(task.getCallback()).ifPresent(callback::putAll);

		// 构造消息
		SendRequest sendRequest = SendRequest.builder()
			.messageTemplateId(String.valueOf(task.getMiddlePlatformTemplateId()))
			.messageParam(MessageParam.builder()
				.variables(task.getTemplateVariables())
				.callback(callback)
				.build())
			.build();
		messageCenter.sendMessage(sendRequest);
	}
}
